package com.xdap.init.service.impl;

import com.xdap.api.constant.ChooseType;
import com.xdap.api.constant.ComponentType;
import com.xdap.api.moudle.business.pojo.FormAreaDto;
import com.xdap.api.moudle.business.pojo.FormMetaAreaDto;
import com.xdap.api.moudle.department.pojo.vo.XdapDepartmentVo;
import com.xdap.api.moudle.formconfig.pojo.DataSelector;
import com.xdap.api.moudle.formconfig.pojo.FormComponent;
import com.xdap.api.moudle.formconfig.pojo.Source;
import com.xdap.api.moudle.formconfig.pojo.XdapFormConfig;
import com.xdap.api.moudle.privateapaas.datamodel.pojo.ModelWithFieldVo;
import com.xdap.api.moudle.user.vo.UserSelectVo;
import com.xdap.common.dao.InitFormDao;
import com.xdap.common.utils.FormDataUtil;
import com.xdap.common.utils.GsonUtil;
import com.xdap.common.utils.InitDateFormatUtil;
import com.xdap.common.utils.TxtUtil;
import com.xdap.init.dao.ModelDao;
import com.xdap.init.dao.ModelFeildDao;
import com.xdap.init.service.ImpExcelConService;
import com.xdap.init.service.InitLastingService;
import com.xdap.init.service.JudgeModelService;
import com.xdap.motor.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @auth lishushu
 * @2023/4/20 18:02
 * @desc {初始化一个导入数据的controller}
 **/

@Slf4j
@Service
public class ImpExcelConServiceImpl implements ImpExcelConService {

    @Autowired
    private InitFormDao initFormDao;
    @Autowired
    private ModelFeildDao modelFeildDao;
    @Autowired
    private ModelDao modelDao;
    @Autowired
    private JudgeModelService judgeModelService;

    @Autowired
    private InitLastingService initLastingService;


    /**
     * @auth lishushu
     * @2023/5/11 17:53
     * @desc {filePath:文件生成地址；formId：表单ID；packageName：生成的包名称；childName：如果是子表的情况下，会带此参数}
     **/
    @Override
    public String init(String filePath, String formId, String packageName) {

        if (!filePath.contains("\\com\\xdap\\")) {
            filePath = filePath + "\\com\\xdap\\" + packageName;
        }
        String result = "";
        XdapFormConfig xdapFormConfig = initFormDao.getXdapFormConfig(formId);
        List<ModelWithFieldVo> modelWithFieldVoList = xdapFormConfig.getModelWithFieldVoList();
        // 先校验模型的字段注释和表单页面上保持一致
        String s = judgeModelService.judgeModelByFormConfig(xdapFormConfig);
        log.info("校验当前模型字段注释和页面上的中文名称保持一致\t：{}w", s);
        // 因为没有页面肯定至少有一个主表，所以这个地方直接处理了
        ModelWithFieldVo mwVoData = modelWithFieldVoList.stream()
                .filter(mwVo ->null !=mwVo.getMainModel() &&  mwVo.getMainModel()).collect(Collectors.toList()).get(0);

        // 初始化名称 定义常用到的对象
        String modelCode = mwVoData.getModelCode();
        String modelName = mwVoData.getModelName();
        String po = TxtUtil.UpperStr(modelCode);
        String upperPo = po.substring(0, 1).toUpperCase() + po.substring(1);
        String logger = "处理" + modelCode + ":" + modelName + "\n";

        // 先生成当前主表对象的PO--调用service生成对应的po对象----------------------------生成持久层
        // TODO 判断当前result是否是成功，如果不成功就不继续了
        result += initLastingService.initLasting(filePath, formId, packageName);


        // 生成serviceimpl
        // 生成service--------------------------------------------------------生成service IMPL

        // 所有的字段配置信息
        List<FormComponent> formComponents = xdapFormConfig.getDetailPage().getFormComponents();
        // 根据formComponents 生成service里面内部的操作
        // --TODO service里面要重复去生成po对象和dao层接口；如果是当前表的情况下，不需要重复生成
        StringBuffer content = new StringBuffer();
        // ##U_import_U##   ##U_otherDao_U##       // ##U_import_U##   ##U_content_U##   ##U_UpperPo_U##  ##U_po_U##
        List<String> sonPoList = null;
        StringBuffer sonPoBuffer = new StringBuffer();

        for (FormComponent fc : formComponents) {
            // 如果有乱码的问题，可以想办法让excel里面展示的字段为字段名称，然后再做判断，这个地方默认不会有乱码的问题
            content.append("\n\n");

            String thisContent = getContent(fc, modelCode, po);
            // 判断是否是获取到的子表，如果是获取到的子表，则需要根据子表po创建controller的方法
            if (thisContent.startsWith(ComponentType.FORM_WIDGET_SON_TABLE)) {
                sonPoBuffer.append(thisContent);
            } else {
                content.append(thisContent);
            }
        }
        if (StringUtils.isNotBlank(sonPoBuffer)) {
            String[] split = sonPoBuffer.toString().split("_###_");
            sonPoList = Arrays.asList(split);
        }


        List<String> sonControllerPoList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(sonPoList)) {
            List<FormComponent> allFormComponents = FormDataUtil.getChildFc(formComponents);
            allFormComponents.addAll(formComponents);
            for (String sonServiceData : sonPoList) {
                String[] split = sonServiceData.split("_##_");
                String sonTableName = split[1];

                FormComponent childFc =
                        allFormComponents.stream().filter(afc ->
                                ComponentType.FORM_WIDGET_SON_TABLE.equals(afc.getComponentType())
                                        && sonTableName.equals(afc.getTableModelCode())
                        ).collect(Collectors.toList()).get(0);
                // 子表注释
                String label = childFc.getLabel();
                // 子表命名
                String sonPo = TxtUtil.UpperStr(sonTableName);
                String upperSonPo = sonPo.substring(0, 1).toUpperCase() + sonPo.substring(1);
                StringBuffer sonContent = new StringBuffer();
                List<FormComponent> children = childFc.getTableColumn();
                for (FormComponent fcChild : children) {
                    sonContent.append(this.getContent(fcChild, sonTableName, sonPo));
                }
                String sonConData = sonContent.toString();
                sonConData = sonConData.replaceAll("data.get\\(\"", "data.get(\"" + label + ".");


                result += createService(packageName, upperSonPo, sonPo, logger + "==" + label, filePath, sonConData);

                String controllerData = sonPo + "_##_" + label;
                sonControllerPoList.add(controllerData);


            }
        }

        // 生成对应对象的model_code

        //
        //生成PO  ##U_content_U##   ##U_UpperPo_U


        // 导入接口，只导入主表数据--暂时先这样 TODO 后面看看是不是也导入副表数据
        content.append("\t\t\t\t" + po + ".setStatus(\"COMPLETED\");\n");
        content.append("\t\t\t\t" + po + ".setTenantId(tenantId);\n");
        content.append("\t\t\t\t" + po + ".setFormId(\"" + formId + "\");\n");

        result += createService(packageName, upperPo, po, logger, filePath, content.toString());
        result += createController(packageName, upperPo, po, logger, filePath, sonControllerPoList);


        return result;
    }

    @SneakyThrows
    private String createService(String packageName, String upperPo, String po, String logger,
                                 String filePath,
                                 String content) {
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        // 添加参数
        VelocityContext context = new VelocityContext();
        // 生成service------------------------------------------------------------------------------------生成service
        context.put("upperPo",upperPo);
        Template tpl = Velocity.getTemplate("base/importExcelService.vm", "UTF-8");

        FileWriter fw  = new FileWriter(filePath+"\\"+upperPo+"Service.java");
        //合并数据到模板
        tpl.merge(context, fw);
        //释放资源
        fw.close();



        String implData = TxtUtil.getResourceData("\\model\\importServiceImpl");
        implData = implData.replaceAll("##U_content_U##", content);
        // 暂时没写
        implData = implData.replaceAll("##U_otherDao_U## ", ""); //暂时没有
        implData = implData.replaceAll("##U_po_U##", po);
        implData = implData.replaceAll("##U_import_U##", "\n"); // 暂时没有
        implData = implData.replaceAll("##U_logger_U##", logger);
        implData = implData.replaceAll("##U_time_U##", InitDateFormatUtil.getCurrentYyyyMmDdHhMiSsCc());

        context.put("upperPo",upperPo);
        context.put("content",content);
        context.put("po",po);
        context.put("packageName",packageName);
        context.put("logger",logger);
        // context.put("import",import);
        // context.put("otherDa",otherDa);
        Template tplImpl = Velocity.getTemplate("base/importExcelServiceImpl.vm", "UTF-8");

        FileWriter fwImpl  = new FileWriter(filePath+"\\"+upperPo+"ServiceImpl.java");
        //合并数据到模板
        tplImpl.merge(context, fwImpl);
        //释放资源
        fwImpl.close();


        return "result";
    }

    private String createController(String packageName, String upperPo, String po, String logger, String filePath,
                                    List<String> sonControllerPoList) {
        // 生成controller
        String controllerData = TxtUtil.getResourceData("\\model\\importExcelController");
        // ##_U_import_U_##
        // ##_U_autowired_U_##
        //##_U_function_U_##
        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        // 添加参数
        VelocityContext context = new VelocityContext();
        context.put("className", "Test");

        // 如果这个表单内有子表，则准备处理子表
        if (CollectionUtils.isNotEmpty(sonControllerPoList)) {
            int autowired = controllerData.indexOf("##_U_autowired_U_##");
            int functionOver = controllerData.indexOf("##_U_function_U_##");
            // 获取到function的方法字符串
            String functionOldStr = controllerData.substring(autowired, functionOver);
            StringBuffer importStr = new StringBuffer();
            StringBuffer functionStr = new StringBuffer();
            for (String sonControllerStr : sonControllerPoList) {
                // 根据规则，第一个是sontable的静态，第二个是子表的po，最后一个是子表的注释
                String[] split = sonControllerStr.split("_##_");
                String sonPo = split[0];
                String logStr = split[1];

                String functionNewStr = functionOldStr;

                String sonUpperPo = sonPo.substring(0, 1).toUpperCase() + sonPo.substring(1);
                importStr.append("import com.xdap.##U_packageName_U##.service.Import")
                        .append(sonUpperPo).append("ExcelService;\n");

                functionNewStr = functionNewStr.replaceAll("##U_packageName_U##", packageName);
                functionNewStr = functionNewStr.replaceAll("##U_UpperPo_U##", sonUpperPo);
                functionNewStr = functionNewStr.replaceAll("##U_po_U##", sonPo);
                functionNewStr = functionNewStr.replaceAll("##U_logger_U##", logger + "-子表：" + logStr);
                functionNewStr = functionNewStr.replaceAll("##U_time_U##", InitDateFormatUtil.getCurrentYyyyMmDdHhMiSsCc());

                functionStr.append("\n\n" + functionNewStr + "\n");


            }
            controllerData = controllerData.replaceAll("##_U_import_U_##", importStr.toString());
            controllerData = controllerData.replaceAll("##_U_autowired_U_##", "");
            controllerData = controllerData.replaceAll("##_U_function_U_##", functionStr.toString());

        }

        // 这个地方再执行一次，是怕上面的没有执行，或者执行后有残余
        controllerData = controllerData.replaceAll("##_U_import_U_##", "");
        controllerData = controllerData.replaceAll("##_U_autowired_U_##", "");
        controllerData = controllerData.replaceAll("##_U_function_U_##", "");


        controllerData = controllerData.replaceAll("##U_packageName_U##", packageName);
        controllerData = controllerData.replaceAll("##U_UpperPo_U##", upperPo);
        controllerData = controllerData.replaceAll("##U_po_U##", po);
        controllerData = controllerData.replaceAll("##U_logger_U##", logger);
        controllerData = controllerData.replaceAll("##U_time_U##", InitDateFormatUtil.getCurrentYyyyMmDdHhMiSsCc());


        // TODO 校验是否有这个controller，如果有这个controller，这个controller里面是否有这个方法，如果有这个同名的方法，则覆盖生成
      //  String result = TxtUtil.createJavaIfNot(filePath + "\\controller", upperPo + "Controller", controllerData);
        return "result";
    }


    private String getContent(FormComponent fc, String modelCode, String po) {


        StringBuffer content = new StringBuffer();
        // 当前字段在导入的时候的状态
        String componentType = fc.getComponentType();
        // 处理tab里面的数据-------------
        if (ComponentType.FORM_ASSOCIATION.equals(componentType) || ComponentType.FORM_EVENT_BUTTON.equals(componentType)) {
            // 关联表单，不做处理---按钮不做处理
            return "";
        } else if (ComponentType.FORM_TAB_LAYOUT.equals(componentType)
                || ComponentType.FORM_TAB_ITEM_LAYOUT.equals(componentType)
                || ComponentType.FORM_WIDGET_SPLIT.equals(componentType)
                || ComponentType.FORM_STATIC_TEXT.equals(componentType)
        ) {
            // FORM_WIDGET_SPLIT 静态分隔符
            // FORM_STATIC_TEXT 静态文本
            // 如果是分页布局等布局中，如果有子表数据的情况下
            List<FormComponent> children = fc.getChildren();
            for (FormComponent fcChild : children) {
                content.append(this.getContent(fcChild, modelCode, po));
            }
            return content.toString();
        } else if (ComponentType.FORM_WIDGET_SON_TABLE.equals(componentType)) {

            String tableModelCode = fc.getTableModelCode();
            return ComponentType.FORM_WIDGET_SON_TABLE + "_##_" + tableModelCode + "_###_";
        }

        // 字段名称，包括表名称和字段名称
        String modelField = fc.getModelField();


        String[] modelFiledData = modelField.split("\\.");
        String tableName = modelFiledData[0];
        if (!tableName.equals(modelCode)) {
            // TODO 暂时只处理主表，副表或者是子表都不处理
            log.info("暂时不出来子表或者附表的导入");
            return "";
        }
        if (modelField == null) {
            // 有些地方会为空，没有字段信息
            log.info("如果字段为空，不做处理");
            return "";
        }


//        String[] modelFiledData = modelField.split("\\.");
//        String tableName = modelFiledData[0];

        String fieldName = modelFiledData[1];
        String fieldParam = TxtUtil.UpperStr(fieldName);
        String upperFieldParam = fieldParam.substring(0, 1).toUpperCase() + fieldParam.substring(1);
        // String tableParam = TxtUtil.UpperStr(tableName);
        String label = fc.getLabel();
        // 是否必填
        Boolean required = fc.getRequired();

        // 当前参数定义名称
        String paramName = "";


        switch (componentType) {
            case ComponentType.FORM_TEXT_INPUT:
                // TODO 流水号未做处理，只当做txt进行处理
            case ComponentType.FORM_DOCUMENT_NUMBER:
                // 大文本
            case ComponentType.FORM_TEXTAREA_INPUT:
                paramName = fieldParam + "Txt";
                // 文本输入
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + "\");\n");

                String defaultValue = fc.getDefaultValue();
                // 有默认值的情况下，如果数据为空，则插入默认值
                if (StringUtils.isNotEmpty(defaultValue)) {
                    content.append("\t\t// 有默认值的情况下，即便是必填也不需要判断必填，如果数据为空，则插入默认值\n");
                    content.append(po + ".set" + upperFieldParam + "(  DataInitUtil.isBlank("
                            + paramName + ") ? \""
                            + defaultValue.replaceAll("\"", "\\\\\"") + "\" : " + paramName + " +\"\"  );\n");
                } else {
                    // 是必填，并且默认值为空
                    content.append(isRequired(paramName, label, required));
                    content.append(po + ".set" + upperFieldParam + "( DataInitUtil.getStr(" + paramName + "));\n");
                }

                break;
            case ComponentType.FORM_SELECT_INPUT:
                paramName = fieldParam + "Dic";
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + "\");\n");

                List<String> selectDefaultValue = fc.getSelectDefaultValue();
                // 必填并且默认值为空的情况下，直接处理必填
                Source source = fc.getSource();
                String sourceId = source.getId();

                String dicData = "\t\t\tif (" + paramName + " != null) {\n" +
                        "\t\t\tString code = DataInitUtil.getCode(" + paramName + ", allDic,\"" + sourceId + "\");\n" +
                        "\t\t\t\tif (code != null) {\n" +
                        "\t\t\t\t" + po + ".set" + upperFieldParam + "( code );\n" +
                        " \t\t\t\t }\n" +
                        " \t\t\t\t}";

                if (CollectionUtils.isNotEmpty(selectDefaultValue)) {
                    content.append("\t\t\t// 有默认值的情况下，当输入值为空的时候，直接插入默认值\n");
                    String defaultData = GsonUtil.toJson(selectDefaultValue);
                    defaultData = defaultData.replace("\"", "\\\\\"");
                    String defaultElse = " else {\n" +
                            // 有默认值，但是没传入数据的情况
                            "\t\t\t\t\t\t" + po + ".set" + upperFieldParam + "( \"" + defaultData + "\"  );\n" +
                            "\t\t\t\t}\n\n";
                    content.append(dicData).append(defaultElse.replaceAll("\"", "\\\\\""));
                } else {
                    content.append("\n\t\t\t// 当没有默认值，并且输入值为空的时候，校验必填");
                    // 是必填，并且默认值为空
                    content.append("\n" + isRequired(paramName, label, required));
                    content.append(dicData + "\n");
                }

                break;

            case ComponentType.FORM_DATA_SELECTOR:
                paramName = fieldParam + "Sel";
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + "\");\n");
                // 是必填
                content.append(isRequired(paramName, label, required));
                DataSelector dataSelector = fc.getDataSelector();
                String otherFormId = dataSelector.getOtherFormId();
                // 初始化另一个formId的主表的信息
                String otherComponent = dataSelector.getOtherComponent();
                // 这里只可能是数据字典、文本的处理，不允许数据选择 选择 数据选择的页面 的 数据选择--如果看不懂，就算了--就这样了
                String otherComponentType = dataSelector.getOtherComponentType();


                if (otherComponentType.equals(ComponentType.FORM_TEXT_INPUT) || otherComponentType.equals(ComponentType.FORM_DOCUMENT_NUMBER)) {
                    XdapFormConfig otherXdapFormConfig = initFormDao.getXdapFormConfig(otherFormId);
                    // 先校验模型的字段注释和表单页面上保持一致  TODO 不校验其他表单
                    // result += judgeModelService.judgeModelByFormConfig(xdapFormConfig);
                    // log.info("校验当前模型字段注释和页面上的中文名称保持一致\t：{}", s);
                    // 直接根据uuid拿到字段
                    List<FormComponent> otherFormComponentList =
                            otherXdapFormConfig.getDetailPage().getFormComponents();
                    // 如果获取不到，就直接报错，说明页面有问题，直接查看问题
                    FormComponent otherFormComponent = otherFormComponentList.stream()
                            .filter(ofc -> ofc.getUuid().equals(otherComponent)).collect(Collectors.toList()).get(0);
                    String otherModelField = otherFormComponent.getModelField();
                    String[] otherModelFieldData = otherModelField.split("\\.");
                    String otherTableName = otherModelFieldData[0];
                    String otherFieldName = otherModelFieldData[1];
                    String dataChooseType = fc.getChooseType();
                    if (ChooseType.SINGLE.equals(dataChooseType)) {
                        content.append("\t\tList<String> " + paramName + "Ids = initSelectDao.getId(\"" + otherTableName +
                                "\", \"" + otherFieldName + "\", " + paramName + ");\n");
                    } else {
                        content.append("\t\tList<String> " + paramName + "Ids = initSelectDao.getIds(\"" + otherTableName +
                                "\", \"" + otherFieldName + "\", " + paramName + ");\n");
                    }


                } else {
                    log.info("------------------" + otherComponentType);
                }

                content.append(isRequiredList(paramName + "Ids", label, required,paramName));
                content.append("\t\t" + po + ".set" + upperFieldParam + "( GsonUtil.toJson(" + paramName + "Ids) );\n");


                break;
            case ComponentType.FORM_NUMBER_INPUT:
                // 金额当做number处理
            case ComponentType.FORM_MONEY_INPUT:
                //defaultValue
                paramName = fieldParam + "Num";
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + "\");\n");

                String defaultNumValueData = fc.getDefaultValue();
                // 必填并且默认值为空的情况下，直接处理必填

                String numData =

                        "\t \n// 先置空，保证数据更新的时候不会确实更新情况 \n " +
                                "\t\t\t\t\t" + po + ".set" + upperFieldParam + "( null  );" +
                                "\t\t\tif (" + paramName + " != null) {\n" +
                                "\t\t\tDouble code = DataInitUtil.getDouble(" + paramName + ");\n" +
                                "\t\t\t\tif (code != null) {\n" +
                                "\t\t\t\t" + po + ".set" + upperFieldParam + "( code );\n" +
                                " \t\t\t\t }\n" +
                                " \t\t\t\t}";

                if (StringUtils.isNotEmpty(defaultNumValueData)) {
                    content.append("\t\t\t// 有默认值的情况下，当输入值为空的时候，直接插入默认值\n");
                    String defaultElse = " else {\n" +
                            // 有默认值，但是没传入数据的情况
                            "\t\t\t\t\t\t" + po + ".set" + upperFieldParam + "( " + defaultNumValueData + "D  );" +
                            "\n\t\t\t\t}\n\n";
                    content.append(numData).append(defaultElse);
                } else {
                    content.append("\t\t\t// 当没有默认值，并且输入值为空的时候，校验必填\n");
                    // 是必填，并且默认值为空
                    content.append("\n" + isRequired(paramName, label, required));
                    content.append(numData + "\n");
                }

                break;
            case ComponentType.FORM_DEPARTMENT_SELECT:
                //defaultValue
                paramName = fieldParam + "Dept";
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + ".名称\");\n");
                String defaultElse = null;
                String defaultDeptValueData = fc.getDefaultValue();
                if ("Now".equals(defaultDeptValueData)) {
                    defaultElse = " else {\n" +
                            // 有默认值，但是没传入数据的情况
                            "\t\t\t\t\t\t" + po + ".set" + upperFieldParam + "(  DataInitUtil.DEPT );\n\t\t\t\t}\n\n";
                    // 当前部门
                } else if ("SpecifyTheDept".equals(defaultDeptValueData)) {
                    List<XdapDepartmentVo> departmentDefaultValue = fc.getDepartmentDefaultValue();
                    List<String> departIds =
                            departmentDefaultValue.stream().map(XdapDepartmentVo::getId).collect(Collectors.toList());
                    defaultDeptValueData = GsonUtil.toJson(departIds);
                    defaultElse = " else {\n" +
                            // 有默认值，但是没传入数据的情况
                            "\t\t\t\t\t\t" + po + ".set" + upperFieldParam + "(  \"" +
                            defaultDeptValueData.replaceAll("\"", "\\\\\"") + "\" );" +
                            "\n\t\t\t\t}\n\n";
                } else {
                    defaultDeptValueData = null;
                }
                // 必填并且默认值为空的情况下，直接处理必填 DataInitUtil.getDept(col5, deptList);

                String deptData = "\t\t\tif (" + paramName + " != null) {\n" +
                        "\t\t\tString code = DataInitUtil.getDept(" + paramName + ", deptList);\n" +
                        "\t\t\t\tif (code != null) {\n" +
                        "\t\t\t\t" + po + ".set" + upperFieldParam + "( code );\n" +
                        " \t\t\t\t }\n" +
                        " \t\t\t\t}";

                if (StringUtils.isNotEmpty(defaultDeptValueData)) {
                    content.append("\t\t\t// 有默认值的情况下，当输入值为空的时候，直接插入默认值\n" +
                            "\t\t\t//当值是DataInitUtil.DEPT的时候默认值根据实际情况去定义DataInitUtil修改参数\n");
                    content.append(deptData).append(defaultElse.replaceAll("\"", "\\\\\""));
                } else {
                    content.append("\t\t\t// 当没有默认值，并且输入值为空的时候，校验必填\n");
                    // 是必填，并且默认值为空
                    content.append("\n" + isRequired(paramName, label, required));
                    content.append(deptData.replaceAll("\"", "\\\\\"") + "\n");
                }


                break;
            case ComponentType.FORM_PEOPLE_SELECT:
                //
                paramName = fieldParam + "User";
                // 文本输入
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + ".账号\");\n");

                String defaultUserValueData = fc.getDefaultValue();
                if ("Now".equals(defaultUserValueData)) {
                    defaultUserValueData = "DataInitUtil.ACCOUNT";
                    // 当前部门
                } else if ("SpecifyThePeople".equals(defaultUserValueData)) {
                    List<UserSelectVo> userSelectDefaultValue = fc.getUserSelectDefaultValue();
                    List<String> userIds =
                            userSelectDefaultValue.stream().map(UserSelectVo::getId).collect(Collectors.toList());
                    defaultUserValueData = GsonUtil.toJson(userIds);
                } else {
                    defaultUserValueData = null;
                }


                // 有默认值的情况下，如果数据为空，则插入默认值
                if (StringUtils.isNotEmpty(defaultUserValueData)) {
                    content.append("\t\t// 有默认值的情况下，即便是必填也不需要判断必填，如果数据为空，则插入默认值\n");

                    if ("DataInitUtil.ACCOUNT".equals(defaultUserValueData)) {
                        content.append(po + ".set" + upperFieldParam + "(  DataInitUtil.isBlank("
                                + paramName + ") ? "
                                + defaultUserValueData + " : " + paramName + " +\"\"  );\n");
                    } else {
                        content.append(po + ".set" + upperFieldParam + "(  DataInitUtil.isBlank("
                                + paramName + ") ? \""
                                + defaultUserValueData.replaceAll("\"", "\\\\\"") + "\" : " + paramName + " +\"\"  );\n");
                    }

                } else {
                    // 是必填，并且默认值为空
                    content.append(isRequired(paramName, label, required));
                    content.append(po + ".set" + upperFieldParam + "( DataInitUtil.getStrCode(" + paramName + "))" +
                            ";\n");
                }

                break;
            case ComponentType.FORM_DATEPICK_INPUT:
                String dateDisplayStyle = fc.getDateDisplayStyle();
                paramName = fieldParam + "Date";
                // 日期输入
                content.append("\t\tObject ").append(paramName + " = data.get(\"" + label + "\");\n");

                String defaultDateValueData = fc.getDefaultValue();
                if ("Now".equals(defaultDateValueData)) {
                    content.append(" Date now" + paramName + " = new Date();");
                    // 当前部门
                } else if (StringUtils.isNotBlank(defaultDateValueData)) {
                    content.append(" Date now" + paramName +
                            " = DataInitUtil.getStr2Date(\"" +
                            defaultDateValueData + "\",\"" + dateDisplayStyle + "\"); \n");

                } else {
                    defaultDateValueData = null;
                }
                content.append(" Date " + paramName +
                        "2 = DataInitUtil.getStr2Date( " + paramName + ",\""
                        + dateDisplayStyle + "\");\n");


                // 有默认值的情况下，如果数据为空，则插入默认值
                if (StringUtils.isNotEmpty(defaultDateValueData)) {
                    content.append("\t\t// 有默认值的情况下，即便是必填也不需要判断必填，如果数据为空，则插入默认值\n");
                    content.append(" if (" + paramName + "2 == null){\n" +
                            "                        " + paramName + "2 = now" + paramName + ";\n" +
                            "                    }\n");
                } else {
                    // 是必填，并且默认值为空
                    content.append(isRequired(paramName + "2", label, required));
                }

                content.append(po + ".set" + upperFieldParam + "( " + paramName + "2);\n");


                break;
            case ComponentType.FORM_WIDGET_AREA:
                paramName = fieldParam;
                // 地区组件

                // 默认数据不为空
                FormAreaDto areaDefault = fc.getAreaDefault();
                FormMetaAreaDto province = areaDefault.getProvince();
                String defaultValueArea = "";

                if (province != null && StringUtils.isNotBlank(province.getName())) {
                    String defaultArea = GsonUtil.toJson(areaDefault);
                    content.append(po + ".set" + upperFieldParam + "( " + paramName + "2);\n");

                    defaultValueArea = " else {" +
                            po + ".set" + upperFieldParam + "( \"" + defaultArea + "\");\n}\n";
                }

                String areaType = fc.getAreaType();
                String isNotBlankData = "!DataInitUtil.isBlank(" + paramName + "Pro)";
                content.append("\t\t//  为了处理数据，不管此下字段是否在表中填写，都做查询\n");
                // 省肯定是有的
                content.append("\t\t//  ---------------------" + label + ".省\n");
                content.append("\t\tObject ").append(paramName + "Pro = data.get(\"" + label + ".省\");\n");

                content.append(isRequired(paramName + "Pro", label + ".省", required));


                content.append("\t\t// -------" + label + ".市\n");
                content.append("\t\tObject ").append(paramName + "City = data.get(\"" + label + ".市\");\n");
                content.append("\t\t//  ---------------------" + label + ".区\n");
                content.append("\t\tObject ").append(paramName + "Area = data.get(\"" + label + ".区\");\n");
                content.append("\t\t//  ---------------------" + label + ".详细地址\n");
                content.append("\t\tObject ").append(paramName + "Detail = data.get(\"" + label + ".详细地址\");\n");

                // 只要是  不单独是省，就有市
                content.append("\t\t\t\t//  会根据实际情况去做是否填写的校验\n");
                if (!"AREA_PROVINCE".equals(areaType)) {
                    content.append(isRequired(paramName + "City", label + ".市", required));
                    isNotBlankData += " && !DataInitUtil.isBlank(" + paramName + "City) \n";
                }
                // 到 区 和 详细地址，肯定有 区
                if ("AREA".equals(areaType) || "AREA_ADDRESS".equals(areaType)) {
                    content.append(isRequired(paramName + "Area", label + ".区", required));
                    isNotBlankData += " && !DataInitUtil.isBlank(" + paramName + "Area) \n";

                    // 只有是详细地址的时候是详细地址
                    if ("AREA_ADDRESS".equals(areaType)) {
                        content.append(isRequired(paramName + "Detail", label + ".详细地址", required));
                        isNotBlankData += " && !DataInitUtil.isBlank(" + paramName + "Detail)";
                    }
                }


                String judgeAreaData =
                        "\t\t\tif (" + isNotBlankData + "){" +
                                //  ---------------------客户地址.市
                                "\t\t\t\tProvinceDataDto province= DataInitUtil.getProvinceData(" + paramName + "Pro,allProvince);\n" +
                                "\t\t\t\tProvinceDataDto city = DataInitUtil.getProvinceData(" + paramName + "City, allProvince);\n" +
                                "\t\t\t\tProvinceDataDto area = DataInitUtil.getProvinceData(" + paramName + "Area, allProvince);\n" +
                                "\t\t\t\tProvinceDataDto address = DataInitUtil.getAddress(" + paramName + "Detail);\n" +
                                "\t\t\t\tProvinceDto dto = new ProvinceDto();\n" +
                                "\t\t\t\tdto.setArea(area);\n" +
                                "\t\t\t\tdto.setProvince(province);\n" +
                                "\t\t\t\tdto.setCity(city);\n" +
                                "\t\t\t\tdto.setAddress(address);\n" +
                                "\t\t\t\t" + po + ".set" + upperFieldParam + "(GsonUtil.toJson(dto));" +
                                "\t\t\t" +
                                "}\n";
                content.append(judgeAreaData);
                content.append(defaultValueArea.replaceAll("\"", "\\\\\""));

                break;
            default:
                break;
        }
        return content.toString();
    }


    public String isRequired(String paramName, String label, boolean isRequired) {
        if (!isRequired) {
            return "";
        }
        // selectDefaultValue
        String result = "\t\t\tif (DataInitUtil.isBlank(" + paramName + ")){\n" +
                "\t\t\t\terrorData.add(\"第{\"+i+\"}行的  " + label + "  数据为空，此字段为必填\");\n" +
                "\t\t\t\tcontinue;\n" +
                "\t\t\t}\n";

        return result;
    }

    public String isRequiredList(String paramName, String label, boolean isRequired, String dataName) {
        if (!isRequired) {
            return "";
        }
        // selectDefaultValue
        String result = "\t\t\tif ( CollectionUtils.isEmpty(" + paramName + ")){\n" +
                "\t\t\t\terrorData.add(\"第{\"+i+\"}行的  " + label + "  数据不为空，此字段为必填，但是根据此字段{"
                + dataName + "}查询出来的ID为空，无法赋值\");\n" +
                "\t\t\t\tcontinue;\n" +
                "\t\t\t}\n";

        return result;
    }


}
